import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

const routes: RouteRecordRaw[] = [
  {
    path: '/test',
    name: 'TestPage',
    component: () => import('@/pages/TestPage.vue'),
    meta: { requiresAuth: true }
  },

  {
    path: '/home',
    name: 'Home',
    component: () => import('@/pages/Home.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/pages/auth/Login.vue'),
    meta: { requiresGuest: true }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/pages/auth/Register.vue'),
    meta: { requiresGuest: true }
  },
  {
    path: '/events',
    name: 'Events',
    component: () => import('@/pages/events/EventList.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/events/create',
    name: 'CreateEvent',
    component: () => import('@/pages/events/CreateEvent.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/events/:id',
    name: 'EventDetail',
    component: () => import('@/pages/events/EventDetail.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/events/:id/edit',
    name: 'EditEvent',
    component: () => import('@/pages/events/EditEvent.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/settings',
    name: 'Settings',
    component: () => import('@/pages/Settings.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/settings/profile',
    name: 'Profile',
    component: () => import('@/pages/settings/Profile.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/settings/diet-types',
    name: 'DietTypes',
    component: () => import('@/pages/settings/DietTypes.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/settings/data-sync',
    name: 'DataSync',
    component: () => import('@/pages/settings/DataSync.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/settings/foods',
    name: 'Foods',
    component: () => import('@/pages/settings/FoodsResponsive.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/nutrition-dashboard',
    name: 'NutritionDashboard',
    component: () => import('@/pages/NutritionDashboard.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/pages/NotFound.vue')
  },
  // 默认重定向
  { path: '/', redirect: '/home' }
]

const router = createRouter({
  history: createWebHistory('/todo/'),
  routes
})

// 路由守卫
router.beforeEach(async (to, _from, next) => {
  // 暂时简化路由守卫，避免循环依赖问题
  // 在实际项目中，可以通过其他方式处理认证状态

  // 检查 localStorage 中的 token
  const token = localStorage.getItem('token')
  const isLoggedIn = !!token

  // 检查是否需要认证
  if (to.meta.requiresAuth && !isLoggedIn) {
    next('/login')
    return
  }

  // 检查是否需要游客状态（已登录用户不能访问登录/注册页）
  if (to.meta.requiresGuest && isLoggedIn) {
    next('/home')
    return
  }

  next()
})

export default router
